# app/api/v1/family/account.py
from fastapi import APIRouter, Depends, Query
from datetime import datetime
from typing import Optional, List

from app.controllers.family.account import account_controller
from app.schemas.family.account import AccountCreate, AccountUpdate
from app.utils.request import RequestHandler
from app.schemas.base.login import CredentialsSchema, JWTOut, JWTPayload
from app.core.auth import get_current_user_required,get_current_superuser


router = APIRouter()

@router.get("/list")
async def list_accounts(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    search: Optional[str] = None,
    order: Optional[str] = None,
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """获取账目记录列表"""
    order_list = order.split(",") if order else ["-created_at"]
    total, items = await account_controller.list_items(page, page_size, search, order_list)
    
    # 转换数据格式
    items_data = []
    for item in items:
        if hasattr(item, 'to_dict'):
            items_data.append(await item.to_dict())
        else:
            items_data.append(item)
    
    data = {
        "items": items_data,
        "total": total,
        "page": page,
        "page_size": page_size
    }
    return RequestHandler.success(data=data, message="获取账目记录成功")

@router.post("/create",)
async def create_account(account_data: AccountCreate,
                         current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
                         ):
    """创建账目记录"""
    record = await account_controller.create_item(account_data)
    data = await record.to_dict() if hasattr(record, 'to_dict') else record
    return RequestHandler.created(data=data, message="账目记录创建成功")

@router.get("/account_info/{id}")
async def get_account_detail(id: int):
    """获取账目记录详情"""
    record = await account_controller.get_item(id)
    data = await record.to_dict() if hasattr(record, 'to_dict') else record
    return RequestHandler.success(data=data, message="获取账目记录详情成功")

@router.put("/account_info/{id}")
async def update_account(id: int, account_data: AccountUpdate,
                         current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
                         ):
    """更新账目记录"""
    record = await account_controller.update_item(id, account_data)
    data = await record.to_dict() if hasattr(record, 'to_dict') else record
    return RequestHandler.success(data=data, message="账目记录更新成功")

@router.delete("/account_info/{id}")
async def delete_account(id: int,
                         current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
                        ):
    """删除账目记录"""
    success = await account_controller.remove_item(id)
    if success:
        return RequestHandler.success(message="账目记录删除成功")
    else:
        return RequestHandler.error(message="账目记录删除失败")

@router.get("/statistics")
async def get_statistics(
    start_datetime: datetime,
    end_datetime: datetime,
    current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
):
    """获取统计数据"""
    stats = await account_controller.get_statistics(start_datetime, end_datetime)
    return RequestHandler.success(data=stats, message="获取统计数据成功")

@router.get("/category-stats")
async def get_category_stats(
    start_datetime: datetime,
    end_datetime: datetime,
    type_: Optional[str] = None,
    current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
):
    """获取分类统计数据"""
    stats = await account_controller.get_category_stats(start_datetime, end_datetime, type_)
    return RequestHandler.success(data=stats, message="获取分类统计成功")

@router.get("/trend")
async def get_monthly_trend(months: int = 6,
                        current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
                        ):
    """获取月度趋势数据"""
    trend_data = await account_controller.get_monthly_trend(months)
    return RequestHandler.success(data=trend_data, message="获取月度趋势成功")